// Update.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Wuapi.h>
#include "wuerror.h"
#include <iostream>
#include <clocale>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	setlocale(LC_CTYPE, "Russian");

	HRESULT hr;
	hr = ::CoInitialize(NULL);

	IUpdateSession* iUpdate;
	IUpdateSearcher* searcher;
	ISearchResult* results;
	BSTR criteria = SysAllocString(L"IsInstalled=0 and Type='Software'");

	hr = ::CoCreateInstance(CLSID_UpdateSession, NULL, CLSCTX_INPROC_SERVER,
		IID_IUpdateSession, (LPVOID*)&iUpdate);
	hr = iUpdate->CreateUpdateSearcher(&searcher);

	wcout << L"Searching for updates ..."<<endl;
	hr = searcher->Search(criteria, &results);
	SysFreeString(criteria);

	switch(hr)
	{
	case S_OK:
		wcout<<L"List of applicable items on the machine:"<<endl;
		break;
	case WU_E_LEGACYSERVER:
		wcout<<L"No server selection enabled"<<endl;
		return 0;
	case WU_E_INVALID_CRITERIA:
		wcout<<L"Invalid search criteria"<<endl;
		return 0;
	}

	IUpdateCollection * updateList;
	IUpdate *updateItem;
	LONG updateSize;
	BSTR updateName;

	results->get_Updates(&updateList);
	updateList->get_Count(&updateSize);

	if (updateSize == 0)
	{
		wcout << L"No updates found"<<endl;
	}

	for (LONG i = 0; i < updateSize; i++)
	{
		updateList->get_Item(i, &updateItem);
		updateItem->get_Title(&updateName);

		wcout<<i+1<<" - "<<updateName<<endl;
	}
	::CoUninitialize();
	wcin.get();
	return 0;
}